package com.uzai.console.web.user;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.uzai.common.enums.AccDetailTypeEnum;
import com.uzai.common.enums.IdentityEnum;
import com.uzai.common.enums.UserBlackTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.annotation.SystemLogType;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.TbUserInfo.TbUserInfoIdDto;
import com.uzai.console.dto.TbUserInfo.TbUserInfoQuery;
import com.uzai.console.dto.TbUserInfo.TbUserInfoUpdateDto;
import com.uzai.console.dto.user.UserUpdateMarketingTagDto;
import com.uzai.console.dto.user.app.*;
import com.uzai.console.dto.user.useraccdetail.UserAccDetailQuery;
import com.uzai.console.dto.user.usertype.UserTypeQuery;
import com.uzai.console.dto.user.wechatuser.WechatUserIdDto;
import com.uzai.console.dto.user.wechatuser.WechatUserIdListDto;
import com.uzai.console.dto.user.wxworkuser.WxworkUserQuery;
import com.uzai.console.dto.user.wxworkuser.WxworkUserUpdateDto;
import com.uzai.console.entity.*;
import com.uzai.console.enums.OperationTypeEnum;
import com.uzai.console.enums.SmsType;
import com.uzai.console.enums.SystemModelEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.user.AppUserBatchService;
import com.uzai.console.service.user.AppUserGroupSendMsgService;
import com.uzai.console.service.user.AppUserService;
import com.uzai.console.service.user.AppUserSyncService;
import com.uzai.console.vo.base.SelectIdVo;
import com.uzai.console.vo.base.SelectKeyVo;
import com.uzai.console.vo.tbuserinfo.TbUserInfoVo;
import com.uzai.console.vo.user.app.AppUserInfoVo;
import com.uzai.console.vo.user.app.AppUserPageVo;
import com.uzai.console.vo.user.useraccdetail.UserAccDetailInfoVo;
import com.uzai.console.vo.user.wechatuser.WechatUserTotalVo;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月25日 20:15
 */
@Api(value = "app会员", tags = "用户管理|app会员")
@ApiSort(15)
@RestController
public class AppUserContoller extends BaseController {

    @Autowired
    private AppUserService appUserService;
    @Autowired
    private AppUserSyncService appUserSyncService;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private PriRewardRuleMapper priRewardRuleMapper;
    @Autowired
    private LadderRatioGroupMapper ladderRatioGroupMapper;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private AppUserGroupSendMsgService appUserGroupSendMsgService;
    @Autowired
    private AppUserBatchService appUserBatchService;
    @Autowired
    private WxpubInfoMapper wxpubInfoMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "分页查询app会员列表", notes = "分页查询app会员列表", response = AppUserPageVo.class)
    @ApiOperationSupport(order = 1)
    @PostMapping("/appUser/findWechatUserList")
    public Object findWechatUserList(@RequestBody AppUserQuery wechatUserQuery) {
        return appUserService.findWechatUserList(wechatUserQuery);
    }

    @ApiOperation(value = "查询app会员详情", notes = "查询app会员详情", response = AppUserInfoVo.class)
    @ApiOperationSupport(order = 2)
    @PostMapping("/appUser/findWechatUserInfo")
    public Object findWechatUserInfo(@RequestBody AppUserIdDto wechatUserIdDto) {
        return appUserService.findWechatUserInfo(wechatUserIdDto);
    }

    @ApiOperation(value = "查询app会员身份下拉列表", notes = "查询app会员身份下拉列表", response = SelectKeyVo.class)
    @ApiOperationSupport(order = 3)
    @PostMapping("/appUser/findIdentityListSelect")
    public Object findIdentityListSelect() {
        List<SelectKeyVo> selectKeyVoList = new ArrayList<>();
        IdentityEnum[] IdentityEnumArr = IdentityEnum.values();
        if (IdentityEnumArr != null && IdentityEnumArr.length > 0) {
            for (IdentityEnum identityEnum : IdentityEnumArr) {
                SelectKeyVo selectKeyVo = new SelectKeyVo();
                //页面显示 身份
                selectKeyVo.setKey(String.valueOf(identityEnum.getId()));
                selectKeyVo.setValue(identityEnum.getDesc());
                selectKeyVoList.add(selectKeyVo);
            }
        }
        return selectKeyVoList;
    }


    @ApiOperation(value = "查询app会员类型", notes = "查询app会员类型", response = SelectIdVo.class)
    @ApiOperationSupport(order = 3)
    @PostMapping("/appUser/findUserTypeList")
    public Object findUserTypeList(@RequestBody UserTypeQuery userTypeQuery) {
        List<SelectIdVo> selectIdVoList = new ArrayList<>();
        List<UserType> userTypeList = userTypeMapper.findByList(userTypeQuery);
        if (userTypeList != null && userTypeList.size() > 0) {
            for (UserType userType : userTypeList) {
                SelectIdVo selectIdVo = new SelectIdVo();
                selectIdVo.setKey(userType.getId());
                //页面显示 身份-类型名称
                UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userType.getGroupId(), userType.getMerId());
                if (userTypeGroup == null) {
                    userTypeGroup = new UserTypeGroup();
                }
                selectIdVo.setValue(Tools.getStr(userTypeGroup.getName()) + "-" + userType.getName() + "（" + IdentityEnum.getById(userType.getIdentity()).getDesc() + "）");
                //是否默认
                selectIdVo.setIsDefault(userType.getIsDefault());
                selectIdVoList.add(selectIdVo);
            }
        }
        return selectIdVoList;
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "查询结果批量删除app会员数据", notes = "查询结果批量删除app会员数据")
    @ApiOperationSupport(order = 5)
    @PostMapping("/appUser/deleteUserSelected")
    public Object deleteUserSelected(@RequestBody AppUserBatchDeleteDto batchDeleteDto) {
        appUserSyncService.deleteUserSelected(batchDeleteDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "多选框批量删除app会员数据（多选框）", notes = "多选框批量删除app会员数据（多选框）")
    @ApiOperationSupport(order = 5)
    @PostMapping("/appUser/deleteUserBatch")
    public Object deleteUserBatch(@RequestBody AppUserIdListDto appUserIdListDto){
        appUserSyncService.deleteUserBatch(appUserIdListDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "单个删除app会员数据", notes = "单个删除app会员数据")
    @ApiOperationSupport(order = 10)
    @PostMapping("/appUser/deleteUserById")
    public Object deleteUserById(@RequestBody AppUserIdDto appUserIdDto){
        //删除成功
        appUserService.deleteUserById(appUserIdDto.getId(), appUserIdDto.getMerId());
        return true;
    }

    @ApiOperation(value = "查询app会员余额总和", notes = "查询app会员余额总和", response = WechatUserTotalVo.class)
    @ApiOperationSupport(order = 21)
    @PostMapping("/appUser/findWechatUserBalanceTotal")
    public Object findWechatUserBalanceTotal(@RequestBody AppUserQuery userQuery) {
        return appUserMapper.findTotalBalance(userQuery);
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "单个修改app会员详情", notes = "单个修改app会员详情")
    @ApiOperationSupport(order = 23)
    @PostMapping("/appUser/updateWechatUser")
    public Object updateWechatUser(@RequestBody AppUserInfoUpdateDto infoUpdateDto) {
        appUserService.updateWechatUserInfo(infoUpdateDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "查询结果批量修改app会员信息", notes = "查询结果批量修改app会员信息")
    @ApiOperationSupport(order = 24)
    @PostMapping("/appUser/batchUpdateToUserSelected")
    public Object batchUpdateToUserSelected(@RequestBody AppUserBatchUpdateDto appUserBatchUpdateDto){

        //AOP切面，封装操作日志内容
        AppUserQuery appUserQuery = appUserBatchUpdateDto.getWechatUserQuery();
        appUserQuery.setMerId(appUserBatchUpdateDto.getMerId());
        //查询总数
        Integer count = appUserMapper.findCount(appUserQuery);
        String aspectOperatorLog = "查询结果批量修改,修改数据共:"+count+"条";


        //判断是否修改了会员余额和积分
        Long merId = appUserBatchUpdateDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }
        boolean updateUserBalanceAndIntegralFlag = false;

        AppUserUpdateDto appUserUpdateDto = appUserBatchUpdateDto.getWechatUserUpdateDto();
        if(appUserUpdateDto.getBalance() != null && appUserUpdateDto.getBalanceType() != null){
            //修改了余额
            updateUserBalanceAndIntegralFlag = true;
            if(Tools.getInteger(appUserUpdateDto.getBalanceType()).intValue() == 0){
                aspectOperatorLog = aspectOperatorLog + "；修改余额:" + appUserUpdateDto.getBalance();
            }else if(Tools.getInteger(appUserUpdateDto.getBalanceType()).intValue() == -1){
                aspectOperatorLog = aspectOperatorLog + "；减少余额:" + appUserUpdateDto.getBalance();
            }else if(Tools.getInteger(appUserUpdateDto.getBalanceType()).intValue() == 1){
                aspectOperatorLog = aspectOperatorLog + "；增加余额:" + appUserUpdateDto.getBalance();
            }
        }

        if(appUserUpdateDto.getIntegral() != null && appUserUpdateDto.getIntegralType() != null){
            //修改了积分
            updateUserBalanceAndIntegralFlag = true;
            if(Tools.getInteger(appUserUpdateDto.getIntegralType()).intValue() == 0){
                aspectOperatorLog = aspectOperatorLog + "；修改积分:" + appUserUpdateDto.getIntegral();
            }else if(Tools.getInteger(appUserUpdateDto.getIntegralType()).intValue() == -1){
                aspectOperatorLog = aspectOperatorLog + "；减少积分:" + appUserUpdateDto.getIntegral();
            }else if(Tools.getInteger(appUserUpdateDto.getIntegralType()).intValue() == 1){
                aspectOperatorLog = aspectOperatorLog + "；增加积分:" + appUserUpdateDto.getIntegral();
            }
        }

        //修改了余额积分，需要发送短信验证
        if(updateUserBalanceAndIntegralFlag){
            if(!uzaiConsoleSysConfig.getDefaultPassword().equals(appUserBatchUpdateDto.getCode())){
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.UPDATE_USER_BALANCE_INTEGRAL.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(appUserBatchUpdateDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(appUserBatchUpdateDto.getCode())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.UPDATE_USER_BALANCE_INTEGRAL.getDesc(), merchant.getMobile()));
            }
        }
        //AOP切面，封装操作日志内容
        appUserBatchUpdateDto.setAspectOperatorLog(aspectOperatorLog);

        appUserSyncService.batchUpdateToUserSelected(appUserBatchUpdateDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "多选框批量修改app会员信息（多选框选择app会员）", notes = "批量修改会员信息（多选框选择app会员）")
    @ApiOperationSupport(order = 25)
    @PostMapping("/appUser/batchUpdateToUserBatch")
    public Object batchUpdateToUserBatch(@RequestBody AppUserUpdateBatchDto appUserUpdateBatchDto){

        //AOP切面，封装操作日志内容
        List<Long> idList = appUserUpdateBatchDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"请选择修改的会员");
        }
        String aspectOperatorLog = "批量修改会员信息(多选框),修改数据共:"+idList.size()+"条";

        //判断是否修改了会员余额和积分
        Long merId = appUserUpdateBatchDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }
        boolean updateUserBalanceAndIntegralFlag = false;

        AppUserUpdateDto appUserUpdateDto = appUserUpdateBatchDto.getWechatUserUpdateDto();
        if(appUserUpdateDto.getBalance() != null && appUserUpdateDto.getBalanceType() != null){
            //修改了余额
            updateUserBalanceAndIntegralFlag = true;
            if(Tools.getInteger(appUserUpdateDto.getBalanceType()).intValue() == 0){
                aspectOperatorLog = aspectOperatorLog + ";修改余额：" + appUserUpdateDto.getBalance();
            }else if(Tools.getInteger(appUserUpdateDto.getBalanceType()).intValue() == -1){
                aspectOperatorLog = aspectOperatorLog + ";减少余额：" + appUserUpdateDto.getBalance();
            }else if(Tools.getInteger(appUserUpdateDto.getBalanceType()).intValue() == 1){
                aspectOperatorLog = aspectOperatorLog + ";增加余额：" + appUserUpdateDto.getBalance();
            }
        }

        if(appUserUpdateDto.getIntegral() != null && appUserUpdateDto.getIntegralType() != null){
            //修改了积分
            updateUserBalanceAndIntegralFlag = true;
            if(Tools.getInteger(appUserUpdateDto.getIntegralType()).intValue() == 0){
                aspectOperatorLog = aspectOperatorLog + ";修改积分：" + appUserUpdateDto.getIntegral();
            }else if(Tools.getInteger(appUserUpdateDto.getIntegralType()).intValue() == -1){
                aspectOperatorLog = aspectOperatorLog + ";减少积分：" + appUserUpdateDto.getIntegral();
            }else if(Tools.getInteger(appUserUpdateDto.getIntegralType()).intValue() == 1){
                aspectOperatorLog = aspectOperatorLog + ";增加积分：" + appUserUpdateDto.getIntegral();
            }
        }

        //修改了余额积分，需要发送短信验证
        if(updateUserBalanceAndIntegralFlag){
            if(!uzaiConsoleSysConfig.getDefaultPassword().equals(appUserUpdateBatchDto.getCode())){
                //获取存在redis中的验证码
                String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.UPDATE_USER_BALANCE_INTEGRAL.getDesc(), merchant.getMobile()));
                //判断验证码是否过期
                if (StringUtils.isBlank(codeByRedis)){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
                }
                //验证码是否正确
                if (!codeByRedis.equals(appUserUpdateBatchDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(appUserUpdateBatchDto.getCode())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
                }
                //验证成功，删除验证码
                redisTemplate.delete(String.format(SmsType.UPDATE_USER_BALANCE_INTEGRAL.getDesc(), merchant.getMobile()));
            }
        }
        //AOP切面，封装操作日志内容
        appUserUpdateBatchDto.setAspectOperatorLog(aspectOperatorLog);

        appUserSyncService.batchUpdateToUserBatch(appUserUpdateBatchDto);
        return true;
    }

    @ApiOperation(value = "查询app会员下级成员", notes = "查询app会员下级成员",response = AppUserPageVo.class)
    @ApiOperationSupport(order = 26)
    @PostMapping("/appUser/findSonUserList")
    public Object findSonUserList(@RequestBody AppFindSonUserListQuery appFindSonUserListQuery){
        return appUserService.findSonUserList(appFindSonUserListQuery);
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "删除app会员下级成员", notes = "删除app会员下级成员")
    @ApiOperationSupport(order = 27)
    @PostMapping("/appUser/deleteSonWechatUser")
    public Object deleteSonWechatUser(@RequestBody AppUserDeleteSonDto appUserDeleteSonDto){
        appUserService.deleteSonWechatUser(appUserDeleteSonDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "批量删除app会员下级成员", notes = "批量删除下级成员")
    @ApiOperationSupport(order = 28)
    @PostMapping("/appUser/deleteSonWechatUserBatch")
    public Object deleteSonWechatUserBatch(@RequestBody AppUserDeleteSonBatchDto appUserDeleteSonBatchDto){
        appUserSyncService.deleteSonWechatUserBatch(appUserDeleteSonBatchDto);
        return true;
    }

    @ApiOperation(value = "查询app会员账户明细类型下拉列表框", notes = "查询app会员账户明细类型下拉列表框", response = SelectIdVo.class)
    @ApiOperationSupport(order = 29)
    @PostMapping("/appUser/findWechatUserAccDetailTypeList")
    public Object findWechatUserAccDetailTypeList(){
        List<SelectIdVo> selectIdVoList = new ArrayList<>();
        for (AccDetailTypeEnum accDetailType : AccDetailTypeEnum.values()){
            SelectIdVo selectIdVo = new SelectIdVo();
            selectIdVo.setKey(Long.valueOf(accDetailType.getValue()));
            selectIdVo.setValue(accDetailType.getDesc());
            selectIdVoList.add(selectIdVo);
        }
        return selectIdVoList;
    }

    @ApiOperation(value = "查询app会员账户明细列表", notes = "查询app会员账户明细列表", response = UserAccDetailInfoVo.class)
    @ApiOperationSupport(order = 30)
    @PostMapping("/appUser/findWechatUserAccDetailList")
    public Object findWechatUserAccDetailList(@RequestBody UserAccDetailQuery wechatUserAccDetailQuery){
        return appUserService.findWechatUserAccDetailList(wechatUserAccDetailQuery);
    }


    @ApiOperation(value = "查询app会员渠道ID列表", notes = "查询app会员渠道ID列表", response = TbUserInfoVo.class)
    @ApiOperationSupport(order = 13)
    @PostMapping("/appUser/findTbUserInfoList")
    public Object findTbUserInfoList(@RequestBody TbUserInfoQuery tbUserInfoQuery){
        return appUserService.findTbUserInfoList(tbUserInfoQuery);
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改app会员渠道ID", notes = "修改app会员渠道ID")
    @ApiOperationSupport(order = 14)
    @PostMapping("/appUser/updateTbUserInfo")
    public Object updateTbUserInfo(@RequestBody TbUserInfoUpdateDto tbUserInfoUpdateDto){
        appUserService.updateTbUserInfo(tbUserInfoUpdateDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "删除app会员渠道ID", notes = "删除app会员渠道ID")
    @ApiOperationSupport(order = 24)
    @PostMapping("/appUser/deleteTbUserInfo")
    public Object deleteTbUserInfo(@RequestBody TbUserInfoIdDto tbUserInfoIdDto){
        appUserService.deleteTbUserInfo(tbUserInfoIdDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改app会员余额积分", notes = "修改app会员余额积分")
    @ApiOperationSupport(order = 15)
    @PostMapping("/appUser/updateWechatUserBalance")
    public Object updateWechatUserBalance(@RequestBody AppUserUpdateBalanceDto appUserUpdateBalanceDto){
        appUserService.updateWechatUserBalance(appUserUpdateBalanceDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.ADD)
    @ApiOperation(value = "app会员加入黑名单", notes = "app会员加入黑名单")
    @ApiOperationSupport(order = 19)
    @PostMapping("/appUser/addBlackUser")
    public Object addBlackUser(@RequestBody AppUserAddBlackDto appUserAddBlackDto){
        appUserService.addBlackUser(appUserAddBlackDto);
        return true;
    }

    @ApiOperation(value = "查询黑名单类型下拉列表框列表", notes = "查询黑名单类型下拉列表框列表", response = SelectIdVo.class)
    @ApiOperationSupport(order = 20)
    @PostMapping("/appUser/findUserBlackTypeList")
    public Object findUserBlackTypeList(){
        List<SelectIdVo> selectIdVoList = new ArrayList<>();

        UserBlackTypeEnum[] userBlackTypeArr = UserBlackTypeEnum.values();

        if(userBlackTypeArr != null  && userBlackTypeArr.length > 0){
            for(UserBlackTypeEnum userBlackType : userBlackTypeArr){
                SelectIdVo selectIdVo =  new SelectIdVo();
                selectIdVo.setKey(Long.valueOf(userBlackType.getValue()));
                selectIdVo.setValue(userBlackType.getDesc());
                selectIdVoList.add(selectIdVo);
            }
        }
        return selectIdVoList;
    }

    @SystemLogType(model = SystemModelEnum.AppUser, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改app会员的会员标签", notes = "修改app会员的会员标签")
    @ApiOperationSupport(order = 18)
    @PostMapping("/appUser/updateSysTags")
    public Object updateSysTags(@RequestBody UserUpdateMarketingTagDto userUpdateMarketingTagDto){
        appUserService.updateSysTags(userUpdateMarketingTagDto);
        return true;
    }


}
